package com.df.common.utils;

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    private static final CloseableHttpClient httpclient;
    public static final String CHARSET = "UTF-8";

    static{
        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(3000).build();
        httpclient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    }

    public static JSONObject sendGet(String url) {
        return sendGet(url,null);
    }

    /**
     * HTTP Get 获取内容
     * @return 页面内容
     */
    public static JSONObject sendGet(String url, Map<String, Object> params) {
        try {
            if(MapUtils.isNotEmpty(params)){
                List<NameValuePair> pairs = new ArrayList<>(params.size());
                params.forEach((key,value) -> pairs.add(new BasicNameValuePair(key, params.get(key).toString())));
                url +="?"+ EntityUtils.toString(new UrlEncodedFormEntity(pairs), CHARSET);
            }
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpclient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode != 200){
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                return null;
            }
            String result = EntityUtils.toString(entity, "utf-8");
            EntityUtils.consume(entity);
            response.close();
            JSONObject jsonObject;
            try {
                jsonObject = JSONObject.parseObject(result);
            } catch (Exception e) {
                jsonObject = new JSONObject();
                jsonObject.put("data", result);
            }
            return jsonObject;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * POST请求，Map形式数据
     * @param url 请求地址
     * @param param 请求数据
     */
    public static JSONObject sendPostMap(String url, Map<String, Object> param) {
        return sendPostMap(url, param, "UTF-8");
    }

    public static JSONObject stringJSONobject(String data){
        data=data.substring(1,data.length()-1);
        data = data.replaceAll("\\\\", "");
        return JSONObject.parseObject(data);
    }

    /**
     * POST请求，Map形式数据
     * @param url 请求地址
     * @param param 请求数据
     * @param charset 编码方式
     */
    public static JSONObject sendPostMap(String url, Map<String, Object> param, String charset) {

        StringBuffer buffer = new StringBuffer();
        if (param != null && !param.isEmpty()) {
            for (Map.Entry<String, Object> entry : param.entrySet()) {
                buffer.append(entry.getKey()).append("=")
                        .append(URLEncoder.encode(entry.getValue() == null ? "" : entry.getValue().toString()))
                        .append("&");

            }
        }
        if (StringUtils.isNotBlank(buffer)) {
            buffer.deleteCharAt(buffer.length() - 1);
        }

        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            if("https".equalsIgnoreCase(realUrl.getProtocol())){
                SSLUtils.ignoreSsl();
            }
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(buffer);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), charset));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        JSONObject jsonObject;
        try {
            jsonObject = JSONObject.parseObject(result);
        } catch (Exception e) {
            jsonObject = new JSONObject();
            jsonObject.put("data", result);
        }
        return jsonObject;
    }
}